package com.cm.projectx.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.text.StrPool;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.cm.projectx.entity.*;
import com.cm.projectx.mapper.ProductInfoMapper;
import com.cm.projectx.mapper.TaskProcessRelationMapper;
import com.cm.projectx.service.IProcessService;
import com.cm.projectx.util.HttpUtils;
import com.cm.projectx.vo.Monitors;
import com.cm.projectx.vo.ProductMonitorRelation;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

@Service
public class ProcessServiceImpl implements IProcessService {
    private Logger logger = LoggerFactory.getLogger(this.getClass());
    @Autowired
    private HttpUtils httpUtils;
    @Autowired
    private ObjectMapper objectMapper;
    @Autowired
    private ProductInfoMapper productInfoMapper;
    @Autowired
    private TaskProcessRelationMapper taskProcessRelationMapper;
    @Value("${spring.low.code.process.query}")
    private String processQueryMethod;

    @Value("${spring.low.code.process.issue}")
    private String issueUrl;

    @Value("${spring.low.code.process.createBy}")
    private String createByUrl;

    public void startAllProcessOfTask(List<ProductMonitorRelation> productMonitorRelations, PriceTask task){
        HashMap<String, List<ProductReq>> monitorMap = new HashMap<>();
        // 新增：存储监测点级别的Map
        HashMap<String, String> monitorLevelMap = new HashMap<>();
        for (ProductMonitorRelation productMonitorRelation : productMonitorRelations) {
            //获取monitorIds数据
            List<String> monitorIds = new ArrayList<>();
            List<Monitors> monitorsList = productMonitorRelation.getMonitors();
            if (monitorsList != null) {
                for (Monitors monitor : monitorsList) {
                    if (monitor != null && monitor.getMonitorId() != null) {
                        monitorIds.add(monitor.getMonitorId());
                        monitorLevelMap.put(monitor.getMonitorId(), monitor.getMonitorLevel());
                    }
                }
            }
            String productId = productMonitorRelation.getProductId();
            //商品
            LambdaQueryWrapper<ProductInfo> query = Wrappers.lambdaQuery();
            ProductInfo productInfo = productInfoMapper.selectOne(query.eq(ProductInfo::getId, productId));

            //类别
            LambdaQueryWrapper<ProductInfo> query2 = Wrappers.lambdaQuery();
            query2.eq(ProductInfo::getId, productInfo.getParentId());
            ProductInfo productTypeInfo = productInfoMapper.selectOne(query2);
            // 获取解析价格类型列表（多选）
            String taskPriceType = task.getPriceType();
            List<String> priceTypes = JSON.parseArray(taskPriceType, String.class);
            for (String priceType : priceTypes) {
                ProductReq productReq = new ProductReq();
                //商品id
                productReq.setProperty1756711574233(productInfo.getId());
                //商品名称
                productReq.setProperty1758014414555(productInfo.getName());
                //商品类别
                productReq.setInput1756697848650(productTypeInfo.getName());
                //规格等级
                productReq.setProperty1756698675664(productInfo.getKind());
                //计量单位
                productReq.setProperty1756698692357(productInfo.getUnit());
                //上期价格
                productReq.setDigit1756697848650((double) 0);
                //本期价格
                productReq.setProperty1756698796775(String.valueOf(0));
                //价格浮动
                productReq.setProperty1757408011440(null);
                //浮动阈值
                productReq.setProperty1758787587191(productMonitorRelation.getFloatingValue());
                //价格类型
                productReq.setProperty1758074143230(priceType);
                //备注
                productReq.setProperty1757407929409(null);
                //序号
                productReq.setSortKey(0);
                //转换数据结构  变成以监测点为键的map
                monitorIds.forEach(monitorId -> {
                    List<ProductReq> products = monitorMap.get(monitorId);
                    if (products == null) {
                        products = new ArrayList<>();
                        products.add(productReq);
                        monitorMap.put(monitorId, products);
                    } else {
                        productReq.setSortKey(products.size() + 1);
                        products.add(productReq);
                    }
                });
            }
        }
        //todo 检测点-商品
        monitorMap.forEach((monitorId, products) -> {
                try {
                    //根据监测点组织信息id获取对应监测点人员信息
                    String userId = getUserId(monitorId);

                    //组装请求信息
                    FormSubmitReq formSubmitReq = new FormSubmitReq();
                    //发起流程时的流程名称使用   任务名称|报价时间   拼接传给低代码20250926
                    formSubmitReq.setProcInstNamePrefix(task.getTaskName() + "|" + task.getStartTime());
                    formSubmitReq.setProcessCode("wjxxbs");
                    //存放监测点对应人员id
                    formSubmitReq.setCreator(userId);
                    //固定值
                    formSubmitReq.setCommitFirstTask("0");
                    FormDataReq fromDataReq = new FormDataReq();
                    //存放监测点对应人员id
                    fromDataReq.setCreator(userId);
                    fromDataReq.setSelectDepartment1758071937554(monitorId);
                    fromDataReq.setSelect1756456950574(task.getScheduleType());
                    //报价日期
                    fromDataReq.setDatePicker1757414426057(task.getStartTime());
                    //报价截止时间
                    fromDataReq.setDateTimePicker1758071962673(task.getEndTime());
                    //任务级别
                    fromDataReq.setInput1758071979910(task.getTaskLevel());
                    //监测点级别（市/区县），取值包括"县"、"市"
                    fromDataReq.setInput1758072003434(monitorLevelMap.get(monitorId));
                    SubModelReq subModelReq = new SubModelReq();
                    //组合商品集
                    subModelReq.setEditableTable1756697848650(products);

                    //构造请求参数
                    formSubmitReq.setFormData(fromDataReq);
                    fromDataReq.setSubModel(subModelReq);

                    String s = objectMapper.writeValueAsString(formSubmitReq);
                    logger.info("即时任务请求参数为：{}", s);
                    //发起流程调用, processId由低代码返回
                    String processId = submitProcess(issueUrl, formSubmitReq);
                    logger.info("流程调用成功,返回流程id{}", processId);
                    //保存任务-流程关联关系
                    TaskProcessRelation taskProcessRelation = new TaskProcessRelation();
                    taskProcessRelation.setId(UUID.randomUUID().toString());
                    taskProcessRelation.setTaskId(task.getId());
                    taskProcessRelation.setProcessId(processId);
                    taskProcessRelation.setStartTime(task.getStartTime());
                    taskProcessRelation.setMonitorId(monitorId);
                    //报价结束时间
                    taskProcessRelation.setEndTime(task.getEndTime());
                    taskProcessRelationMapper.insert(taskProcessRelation);
                } catch (Exception e) {
                    logger.error("流程发起异常, 监测点：{}", monitorId, e);
                    throw new RuntimeException("流程发起失败，监测点: " + monitorId, e);
                }
        });
    }

    public String getUserId(String key) {
        try {
            // 构建请求参数
            Map<String, Object> params = new HashMap<>();
            params.put("parentId", key);
            params.put("status", 1);
            params.put("tenantId", 1);
            // 调用接口获取响应
            JSONObject responseJson = httpUtils.get(createByUrl, params, JSONObject.class);
            // 检查请求是否成功
            if (responseJson != null && responseJson.getBool("result")) {
                objectMapper.writeValueAsString(responseJson);
                logger.info("调用用户请求接口成功，返回参数为：{}",responseJson);
                JSONArray dataArray = responseJson.getJSONArray("data");
                if (dataArray != null && !dataArray.isEmpty()) {
                    // 遍历查找第一个group=false的项
                    for (int i = 0; i < dataArray.size(); i++) {
                        JSONObject item = dataArray.getJSONObject(i);
                        if (item.containsKey("group") && !item.getBool("group")) {
                            return item.getStr("id");
                        }
                    }
                }
            }
            logger.warn("未找到符合条件的用户数据，parentId: {}", key);
            throw new RuntimeException("未找到符合条件的用户数据");
        } catch (Exception e) {
            logger.error("获取用户ID时发生错误，parentId: {}", key, e);
          throw new RuntimeException("获取用户ID时发生错误",e);
        }
    }
    //流程处理
    public String submitProcess(String url, FormSubmitReq formSubmitReq) {
        try {
            // 发送请求
            String jsonResponse = httpUtils.postJson(url, formSubmitReq, String.class);
            // 解析响应
            JsonNode rootNode = objectMapper.readTree(jsonResponse);

            // 检查API调用是否成功
            if (rootNode.has("result") && rootNode.get("result").asBoolean()) {
                // 提取processId (instanceId)
                JsonNode dataNode = rootNode.get("data");
                if (dataNode != null && dataNode.has("instanceId")) {
                    return dataNode.get("instanceId").asText();
                } else {
                    throw new RuntimeException("API响应中缺少data或instanceId字段");
                }
            } else {
                // 处理API调用失败的情况
                String errorCode = rootNode.has("errorCode") ? rootNode.get("errorCode").asText() : "未知错误";
                String errorMsg = rootNode.has("errorMsg") ? rootNode.get("errorMsg").asText() : "无错误信息";
                throw new RuntimeException("API调用失败: " + errorCode + " - " + errorMsg);
            }
        } catch (Exception e) {
            throw new RuntimeException("处理API响应时发生异常: " + e.getMessage(), e);
        }
    }

    @Override
    public Object processList(int taskId) {
        ArrayList<Object> processList = new ArrayList<>();
        List<TaskProcessRelation> taskProcessRelations = taskProcessRelationMapper.selectList(Wrappers.<TaskProcessRelation>lambdaQuery().eq(TaskProcessRelation::getTaskId, taskId));
        List<String> processIds = taskProcessRelations.stream().map(TaskProcessRelation::getProcessId).collect(Collectors.toList());

        //获取流程id与流程任务关联对象映射
        Map<String, TaskProcessRelation> processStartTimeMapping = taskProcessRelations.stream().collect(Collectors.toMap(TaskProcessRelation::getProcessId, Function.identity()));

        //使用接口查询流程实例信息
        System.out.println("请求流程实例id集合=" + processIds);
        JSONObject response = httpUtils.get(processQueryMethod, MapUtil.of("procInstId", StrUtil.join(StrPool.COMMA, processIds)), JSONObject.class);
        System.out.println("response:" + response);
        if(Boolean.TRUE.equals(response.get("result"))) {
            JSONArray processArray = (JSONArray) response.get("data");
            for (Object o : processArray) {
                HashMap<String, Object> processMap = new HashMap<>();
                JSONObject process = (JSONObject) o;
                JSONObject dataInstance = (JSONObject) process.get("dataInstance");
                if(dataInstance != null) {
                    Object monitorPointStr = dataInstance.get("selectDepartment1758071937554");
                    JSONArray monitorPointArray = JSONUtil.parseArray(monitorPointStr);
                    if(CollUtil.isNotEmpty(monitorPointArray)) {
                        Object monitorPointName = ((JSONObject) monitorPointArray.get(0)).get("name");
                        processMap.put("monitorPointName", monitorPointName);
                    }
                }
                TaskProcessRelation curTaskProcessRelation = processStartTimeMapping.get(process.get("processInstanceId"));
                curTaskProcessRelation = curTaskProcessRelation == null ? new TaskProcessRelation() : curTaskProcessRelation;
                processMap.put("date", curTaskProcessRelation.getStartTime());
                processMap.put("endDate", curTaskProcessRelation.getEndTime());
                processMap.put("startUserName", process.get("processStartUserName"));
                processMap.put("username", process.get("taskAssigneeName"));
                processMap.put("status", "finished".equals(process.get("processInstanceStatus")) ? "已完成" : "未完成");
                processList.add(processMap);
            }
        }

        return processList;
    }
}
